import { Canvas } from '@react-three/fiber';
import { FC, useEffect, useRef, useState } from 'react';
import { Perf } from "r3f-perf"
import { ScrollControls, OrbitControls, Line, Environment, GizmoHelper, GizmoViewport } from '@react-three/drei';
import type { OrbitControls as OrbitControlsImpl } from 'three-stdlib';

import {useStore} from './store'
import { Cube } from './cube';
import { Earth } from './earth';
import { InstanceSamplerMesh } from './InstancedMeshs';

const DemoLine: FC = () => {
  const [lineData, setLineData] = useState<any>([[0, 0, 0], [3, 4, 1], [3, 3, 3]]);

  setTimeout(() => {
    setLineData([[1, 1, 2], [3, 3, 3], [2, -2, 1], [0, 1, 2]])
  }, 2000);
  return <>
    <Line
      points={lineData}               // Array of points, Array<Vector3 | Vector2 | [number, number, number] | [number, number] | number>
      color="black"                   // Default
      lineWidth={2}                   // In pixels (default)
      // segments                     // If true, renders a THREE.LineSegments2. Otherwise, renders a THREE.Line2
      dashed={false}                  // Default
    />
  </>
}

const Init: React.FC = () => {

  return (
    <div className='full center'>
      <Canvas>
        {/* <DemoLine /> */}
        <ScrollControls infinite pages={4}>
          <Earth />
        </ScrollControls>

        <InstanceSamplerMesh />

        <Cube 
          openPivot
        />
        <Environment preset='forest' background />

        <CameraControls />
        <ambientLight intensity={0.7} />
        <directionalLight position={[2, 2, 5]} intensity={1} />

        <GizmoHelper alignment="bottom-right" margin={[100, 100]}>
          <GizmoViewport labelColor="white" />
        </GizmoHelper>

        {/* <Perf position="right-left" /> */}
      </Canvas>
    </div>
  );
};

const CameraControls: FC = () => {
  const ref = useRef<OrbitControlsImpl>(null!)

  const isHoveredEarth = useStore((state: any) => state.hovered);

  useEffect(() => {
    // console.log('ref.current', ref.current, ref.current.enabled)
    console.log('watch - isHoveredEarth', isHoveredEarth);

    // 鼠标 hover Earth 时，不能使用 OrbitControls
    ref.current.enabled = !isHoveredEarth;

  }, [isHoveredEarth]);

  return <>
    <OrbitControls ref={ref} makeDefault />
  </>
}

export default Init;
